package com.wudl.govern.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wudl.govern.domain.*;
import com.wudl.govern.mapper.*;
import com.wudl.govern.service.ErrorTaskLogService;
import com.wudl.govern.utils.QualityMsgUtil;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author ：wudl
 * @date ：Created in 2022-04-05 21:41
 * @description：
 * @modified By：
 * @version: 1.0
 */

@Service
public class ErrorTaskLogServiceImpl implements ErrorTaskLogService {
    private final Logger logger = LoggerFactory.getLogger(ControlTaskServiceImpl.class);

    @Resource
    private ErrorTaskLogMapper errorTaskLogMapper;
    @Resource
    private MonitorReportMapper monitorReportMapper;
    @Resource
    private ReportDetailMapper reportDetailMapper;
    @Resource
    private QualityExceptionReportMapper qualityExceptionReportMapper;
    @Resource
    private ErrorDataFileMapper errorDataFileMapper;

    /***
     * 批量添加问题数据
     * @param rules
     * @return
     */
    @Override
    public Integer batchInsertErrorLog(String rules) {
        try {
            List<ErrorTaskLog> list = JSON.parseArray(rules, ErrorTaskLog.class);
            logger.info("list:" + list);
            int batch = errorTaskLogMapper.batchAddErrorTask(list, new Date());
            return batch;
        } catch (Exception e) {
            logger.error(QualityMsgUtil.BATCH_ADD_TASK_LOG_ERROR, e);
            return -100;
        }
    }

    /***
     * 插入监控报告信息
     * @param report                        报告信息
     * @param reportDetails                 报告详情列表
     * @return
     */
    @Override
    public Integer insertReports(String report, String reportDetails, String finalScore) {
        try {
            int rNum;
            Date date = new Date();
            MonitorReport rpt = JSONObject.parseObject(report, MonitorReport.class);
            Map<String, String> rptMap = monitorReportMapper.selectReportByTaskId(rpt.getTaskId() + "");
            if (rptMap == null) {
                rpt.setCreateDate(date);
                rpt.setExecutionNum(1);
                rNum = monitorReportMapper.insertSelective(rpt);
            } else {
                //如果不是第一次监控只叠加执行次数和数据状态
                rpt.setId(Integer.parseInt(String.valueOf(rptMap.get("id"))));
                rNum = monitorReportMapper.updateMonitorinfo(rpt.getTaskId() + "");
            }
            if (rNum < 1) {
                return 1;
            } else {
                int reportId = rpt.getId();
                List<ReportDetail> list = JSON.parseArray(reportDetails, ReportDetail.class);
                int rdNum = reportDetailMapper.batchAddReportDetail(list, date, reportId + "", finalScore);
                if (rdNum < 1) {
                    return -100;
                }
                return 1;
            }
        } catch (Exception e) {
            logger.error(QualityMsgUtil.ADD_REPORT_ERROR, e);
            return -100;
        }
    }

    /***
     * 添加质量异常单
     * @param exception
     * @return
     */
    @Override
    public Integer insertExceptionReport(JSONObject exception) {
        try {
            int surplus = 30;
            Date now = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String nowStr = sdf.format(now);
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, surplus);
            String solve = sdf.format(calendar.getTime());

            QualityExceptionReport rpt = JSON.toJavaObject(exception, QualityExceptionReport.class);
            rpt.setGenerateDate(sdf.parse(nowStr));
            rpt.setSolveDate(sdf.parse(solve));
            rpt.setSurplusDate(surplus);
            rpt.setCreateDate(now);
            int qerNum = qualityExceptionReportMapper.insertSelective(rpt);
            if (qerNum < 1) {
                return -100;
            }
            return rpt.getId();
        } catch (Exception e) {
            logger.error(QualityMsgUtil.ADD_EXCEPTION_REPORT_ERROR, e);
            return -100;
        }
    }

    /***
     * 记录错误数据文件地址
     * @param errorFile
     * @return
     */
    @Override
    public Integer insertErrorDataFiles(String errorFile) {
        try {
            List<ErrorDataFile> list = JSON.parseArray(errorFile, ErrorDataFile.class);
            logger.info("list:" + list);
            int batch = errorDataFileMapper.batchAddErrorFile(list, new Date());
            if (batch < 1) {
                return  -100;
            } else {
                return 1;
            }
        } catch (Exception e) {
            logger.error(QualityMsgUtil.ADD_ERROR_FILE_ERROR, e);
            return -100;
        }
    }

    /***
     * 修改异常单剩余天数
     */
    @Override
    public void updateSurplusDate() {
        qualityExceptionReportMapper.updateSurplusDate();
    }

    /***
     * 插入监控报告信息
     * @param report                        报告信息
     * @param reportDetail                 报告详情列表
     * @return
     */
    @Override
    public Integer insertReportByError(String report, String reportDetail) {
        try {
            int rNum;
            Date date = new Date();
            MonitorReport rpt = JSONObject.parseObject(report, MonitorReport.class);
            Map<String, String> rptMap = monitorReportMapper.selectReportByTaskId(rpt.getTaskId() + "");
            if (rptMap == null) {
                rpt.setCreateDate(date);
                rpt.setExecutionNum(1);
                rNum = monitorReportMapper.insertSelective(rpt);
            } else {
                rpt.setId(Integer.parseInt(String.valueOf(rptMap.get("id"))));
                rpt.setExecutionNum(rptMap.get("execution_num") == null ? 1 : Integer.parseInt(String.valueOf(rptMap.get("execution_num"))) + 1);
                rpt.setDataState(1);
                rNum = monitorReportMapper.updateByPrimaryKeySelective(rpt);
            }
            if (rNum < 1) {
                return -100;
            } else {
                int reportId = rpt.getId();
                ReportDetail reportDetail1 = JSON.parseObject(reportDetail, ReportDetail.class);
                reportDetail1.setReportId(reportId);
                reportDetail1.setCreateDate(date);
                int rdNum = reportDetailMapper.insertSelective(reportDetail1);
                if (rdNum < 1) {
                    return -100;
                }
                return 1;
            }
        } catch (Exception e) {
            logger.error(QualityMsgUtil.ADD_REPORT_ERROR, e);
            return -100;
        }
    }
}
